/**
 * 获取月份的天数
 * @param {年} year 
 * @param {月} month 
 */
export function getDaysInMonth(obj) {
  //获取上个月最后几天(数组)
  const lastCalendarData = obj?.lastCalendarData || getLastCalendarData(obj)
  //获取当前月份的天数
  const daysInMonth =  getDaysInTargetMonth(obj)
  const daysInMonthArr = []
  for (let i = 0; i < daysInMonth; i++) {
    daysInMonthArr.push(i + 1)
  }
  //将上个月的最后几天和当月的天数合并成数组渲染
  return lastCalendarData.concat(daysInMonthArr)
}

/**
 * 获取目标月的天数
 * @param  obj 
 * @returns 
 */
export function getDaysInTargetMonth(obj) {
  const year = obj?.year || getCurrentYear()
  const month = obj?.month || getCurrentMonth()
  const day = 0
  const daysInMonth =  new Date(year, month, day).getDate()
  return daysInMonth
}

/**
 * 获取当前年份
 * @returns 
 */
export function getCurrentYear() {
  const date = new Date();
  return date.getFullYear()
}

/**
 * 获取当前月份
 * @returns 
 */
 export function getCurrentMonth() {
  const date = new Date();
  return date.getMonth() + 1
}

/**
 * 获取当前日
 * @returns 
 */
 export function getCurrentDay() {
  const date = new Date();
  return date.getDate()
}

/**
 * 获取第一天是周几
 * @returns 
 */
 export function getFirstDayOfWeek(obj) {
  const year = obj?.year || getCurrentYear()
  const month = obj?.month || getCurrentMonth()
  const date = new Date(`${month}/1/${year}`);
  return date.getDay()
}

/**
 * 获取上个月的最后几天
 * @param arg 
 * @returns 
 */
export function getLastCalendarData(arg) {
  let year = arg?.year || getCurrentYear()
  let month = arg?.month || getCurrentMonth()
  month = month - 1
  //如果减去1之后小于1 则计算上一年
  if (month < 1) {
    month = 12;
    year --;
  }
  const obj = {
    month,
    year
  }
  //获取当月第一天是周几
  const firstDayOfWeek = getFirstDayOfWeek(arg)
  //获取上个月一共有多少天
  const daysInLastMonth = getDaysInTargetMonth(obj)
  let lastCalendarData = []
  //遍历上个月的天数
  for (let i = 0; i < daysInLastMonth; i++) {
    //以当月第一天是周几的角标为起点计算上个月的最后几天
    let startIndex = daysInLastMonth - firstDayOfWeek
    if (i >= startIndex) {
      lastCalendarData.push(i + 1)
    }
  }
  return lastCalendarData
}